package xw.qxypt.modules.baseinfo.service.impl;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import xw.qxypt.common.utils.BaseTree;
import xw.qxypt.common.utils.Constant;
import xw.qxypt.common.utils.PageUtils;
import xw.qxypt.common.utils.Query;

import xw.qxypt.modules.baseinfo.dao.LhpInstallationPointDao;
import xw.qxypt.modules.baseinfo.entity.*;
import xw.qxypt.modules.baseinfo.service.*;
import xw.qxypt.modules.socket.entity.DataCollection;


@Service("lhpInstallationPointService")
public class LhpInstallationPointServiceImpl extends ServiceImpl<LhpInstallationPointDao, LhpInstallationPointEntity> implements LhpInstallationPointService {
    @Autowired
    private LhpHighwaySectionService lhpHighwaySectionService;
    @Autowired
    private LhpDataRoadDetectorService detectorService;
    @Autowired
    private LhpDataVisibilityService visibilityService;
    @Autowired
    private LhpDataWeatherStationService weatherStationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String pointName = (String)params.get("pointName");
        IPage<LhpInstallationPointEntity> page = this.page(
                new Query<LhpInstallationPointEntity>().getPage(params),
                new QueryWrapper<LhpInstallationPointEntity>()
                        .like(StringUtils.isNotBlank(pointName),"point_name", pointName)
                        .apply(params.get(Constant.SQL_FILTER) != null, (String)params.get(Constant.SQL_FILTER))
        );
        List<LhpHighwaySectionEntity> waysectList=lhpHighwaySectionService.list();
        List<LhpInstallationPointEntity> list=page.getRecords();
        for(LhpInstallationPointEntity entity:list){
            for(LhpHighwaySectionEntity lhpHighwaySectionEntity:waysectList){
                if(entity.getWaysectId().equals(lhpHighwaySectionEntity.getId())){
                    entity.setWaysectName(lhpHighwaySectionEntity.getRoadName());
                }
            }
        }
        return new PageUtils(page);
    }

    @Override
    public List<BaseTree> pointTree() {
        List<LhpInstallationPointEntity> pointList=this.list();
        List<LhpHighwaySectionEntity> waysectList =lhpHighwaySectionService.list();
        List<BaseTree> treeList=new ArrayList<>();

        for (LhpHighwaySectionEntity waysect:waysectList){
            boolean bl=true;
            for (LhpInstallationPointEntity pointEntity:pointList){
               if(pointEntity.getWaysectId().equals(waysect.getId())){
                   if(bl){
                       BaseTree tree=new BaseTree();
                       tree.setId(waysect.getId());
                       tree.setName(waysect.getRoadName());
                       treeList.add(tree);
                       bl=false;
                   }
                   BaseTree tree=new BaseTree();
                   tree.setId(pointEntity.getId());
                   tree.setParentId(pointEntity.getWaysectId());
                   tree.setName(pointEntity.getPointName());
                   treeList.add(tree);
               }
            }
        }
        return treeList;
    }

    @Override
    public List<LhpInstallationPointEntity> getPointByUserId(Long userId) {
        List<LhpInstallationPointEntity> list=this.baseMapper.getPointByUserId(userId);
        //去除凝冰摄像机dtu
        Iterator<LhpInstallationPointEntity> iterator = list.iterator();
        while (iterator.hasNext()) {
            LhpInstallationPointEntity point = iterator.next();
            if (point.getPointCode().startsWith("AB"))
                iterator.remove();
        }
        return list;
    }

    @Override
    public Map<String,LhpDataEquipmentinfoEntity> getDataByUserId(Long userId) {
        //查询用户下所有安装点
        List<LhpInstallationPointEntity> pointList=getPointByUserId(userId);
        List<String> pointIds=new ArrayList<>();
        for (LhpInstallationPointEntity point:pointList) {
            pointIds.add(point.getId());
        }
        //根据安装点查询实时设备数据
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, -5);
        //地面探测器数据
        List<LhpDataRoadDetectorEntity> detectorList=detectorService.list(
                new QueryWrapper<LhpDataRoadDetectorEntity>()
                        .in("point_id", pointIds)
                        .gt("data_time",calendar.getTime())
        );
        //能见度数据
        List<LhpDataVisibilityEntity> visibilityList=visibilityService.list(
                new QueryWrapper<LhpDataVisibilityEntity>()
                        .in("point_id", pointIds)
                        .gt("data_time",calendar.getTime())
        );
        //气象站数据
        List<LhpDataWeatherStationEntity> weatherStationList=weatherStationService.list(
                new QueryWrapper<LhpDataWeatherStationEntity>()
                        .in("point_id", pointIds)
                        .gt("data_time",calendar.getTime())
        );
        //重新组织数据
        Map<String,LhpDataEquipmentinfoEntity> dataMap= new HashMap<>();
        //地面数据
        for (LhpDataRoadDetectorEntity roadDetector:detectorList) {
            if(dataMap.containsKey(roadDetector.getPointId())){
                LhpDataEquipmentinfoEntity equipmentinfo=dataMap.get(roadDetector.getPointId());
                if(roadDetector.getWaterFilmHeight()!=null){
                    equipmentinfo.setWaterFilmHeight(roadDetector.getWaterFilmHeight());
                    if(NumberUtils.isNumber(roadDetector.getWaterFilmHeight()) && Double.parseDouble(roadDetector.getWaterFilmHeight()) > 0) {
                        equipmentinfo.setWaterFilmHeightLevel("#ff9933");
                    }
                }
                if(roadDetector.getRoadCondition()!=null){
                    String rc = roadDetector.getRoadCondition();
                    String roadConditionLevel="";
                    if("10".equals(rc)) {
                        rc = "干";
                    }else if("15".equals(rc)) {
                        rc = "潮";
                    }else if("20".equals(rc)) {
                        rc = "湿";
                    }else if("25".equals(rc)) {
                        rc = "潮含盐";
                    }else if("30".equals(rc)) {
                        rc = "湿含盐";
                    }else if("35".equals(rc)) {
                        roadConditionLevel="#ff6766";
                        rc = "冰";
                    }else if("40".equals(rc)) {
                        roadConditionLevel="#ff6766";
                        rc = "雪";
                    }else if("45".equals(rc)) {
                        roadConditionLevel="#ff6766";
                        rc = "霜";
                    }
                    equipmentinfo.setRoadCondition(rc);
                    equipmentinfo.setRoadConditionLevel(roadConditionLevel);
                }
                if (roadDetector.getRoadSurfaceTemp()!=null){
                    equipmentinfo.setRoadSurfaceTemp(roadDetector.getRoadSurfaceTemp());
                    if((NumberUtils.isNumber(roadDetector.getRoadSurfaceTemp()) && Double.parseDouble(roadDetector.getRoadSurfaceTemp()) < 0)||(NumberUtils.isNumber(roadDetector.getRoadSurfaceTemp()) && Double.parseDouble(roadDetector.getRoadSurfaceTemp()) < 0)){
                        equipmentinfo.setRoadSurfaceTempLevel("#ff9933");
                    }
                }
                if(roadDetector.getFriction()!=null){
                    equipmentinfo.setFriction(roadDetector.getFriction());
                    if(NumberUtils.isNumber(roadDetector.getFriction()) && Double.parseDouble(roadDetector.getFriction()) < 0.3) {
                        equipmentinfo.setFrictionLevel("#ff6766");
                    } else if(NumberUtils.isNumber(roadDetector.getFriction()) && Double.parseDouble(roadDetector.getFriction()) < 0.55) {
                        equipmentinfo.setFrictionLevel("#ff9933");
                    }
                }
            }else{
                LhpDataEquipmentinfoEntity equipmentinfo=new LhpDataEquipmentinfoEntity();
                if(roadDetector.getWaterFilmHeight()!=null){
                    equipmentinfo.setWaterFilmHeight(roadDetector.getWaterFilmHeight());
                    if(NumberUtils.isNumber(roadDetector.getWaterFilmHeight()) && Double.parseDouble(roadDetector.getWaterFilmHeight()) > 0) {
                        equipmentinfo.setWaterFilmHeightLevel("#ff9933");
                    }
                }
                if(roadDetector.getRoadCondition()!=null){
                    String rc = roadDetector.getRoadCondition();
                    String roadConditionLevel="";
                    if("10".equals(rc)) {
                        rc = "干";
                    }else if("15".equals(rc)) {
                        rc = "潮";
                    }else if("20".equals(rc)) {
                        rc = "湿";
                    }else if("25".equals(rc)) {
                        rc = "潮含盐";
                    }else if("30".equals(rc)) {
                        rc = "湿含盐";
                    }else if("35".equals(rc)) {
                        roadConditionLevel="#ff6766";
                        rc = "冰";
                    }else if("40".equals(rc)) {
                        roadConditionLevel="#ff6766";
                        rc = "雪";
                    }else if("45".equals(rc)) {
                        roadConditionLevel="#ff6766";
                        rc = "霜";
                    }
                    equipmentinfo.setRoadCondition(rc);
                    equipmentinfo.setRoadConditionLevel(roadConditionLevel);
                }
                if (roadDetector.getRoadSurfaceTemp()!=null){
                    equipmentinfo.setRoadSurfaceTemp(roadDetector.getRoadSurfaceTemp());
                    if((NumberUtils.isNumber(roadDetector.getRoadSurfaceTemp()) && Double.parseDouble(roadDetector.getRoadSurfaceTemp()) < 0)||(NumberUtils.isNumber(roadDetector.getRoadSurfaceTemp()) && Double.parseDouble(roadDetector.getRoadSurfaceTemp()) < 0)){
                        equipmentinfo.setRoadSurfaceTempLevel("#ff9933");
                    }
                }
                if(roadDetector.getFriction()!=null){
                    equipmentinfo.setFriction(roadDetector.getFriction());
                    if(NumberUtils.isNumber(roadDetector.getFriction()) && Double.parseDouble(roadDetector.getFriction()) < 0.3) {
                        equipmentinfo.setFrictionLevel("#ff6766");
                    } else if(NumberUtils.isNumber(roadDetector.getFriction()) && Double.parseDouble(roadDetector.getFriction()) < 0.55) {
                        equipmentinfo.setFrictionLevel("#ff9933");
                    }
                }
                dataMap.put(roadDetector.getPointId(),equipmentinfo);
            }
        }
        //能见度数据
        for (LhpDataVisibilityEntity visibility: visibilityList) {
            if(dataMap.containsKey(visibility.getPointId())){
                LhpDataEquipmentinfoEntity equipmentinfo=dataMap.get(visibility.getPointId());
                if(visibility.getVisibility()!=null){
                    equipmentinfo.setVisibility(visibility.getVisibility());
                    if(NumberUtils.isNumber(visibility.getVisibility()) && Double.parseDouble(visibility.getVisibility()) < 500) {
                        equipmentinfo.setVisibilityLevel("#ff6766");
                    } else if(NumberUtils.isNumber(visibility.getVisibility()) && Double.parseDouble(visibility.getVisibility()) < 1000) {
                        equipmentinfo.setVisibilityLevel("#ff9933");
                    } else if(NumberUtils.isNumber(visibility.getVisibility()) && Double.parseDouble(visibility.getVisibility()) < 2000) {
                        equipmentinfo.setVisibilityLevel("#6ca0cd");
                    }
                }
            }else {
                LhpDataEquipmentinfoEntity equipmentinfo=new LhpDataEquipmentinfoEntity();
                if(visibility.getVisibility()!=null){
                    equipmentinfo.setVisibility(visibility.getVisibility());
                    if(NumberUtils.isNumber(visibility.getVisibility()) && Double.parseDouble(visibility.getVisibility()) < 500) {
                        equipmentinfo.setVisibilityLevel("#ff6766");
                    } else if(NumberUtils.isNumber(visibility.getVisibility()) && Double.parseDouble(visibility.getVisibility()) < 1000) {
                        equipmentinfo.setVisibilityLevel("#ff9933");
                    } else if(NumberUtils.isNumber(visibility.getVisibility()) && Double.parseDouble(visibility.getVisibility()) < 2000) {
                        equipmentinfo.setVisibilityLevel("#6ca0cd");
                    }
                }
                dataMap.put(visibility.getPointId(),equipmentinfo);
            }
        }
        //气象站数据
        for (LhpDataWeatherStationEntity weatherStation:weatherStationList) {
            if(dataMap.containsKey(weatherStation.getPointId())){
                LhpDataEquipmentinfoEntity equipmentinfo=dataMap.get(weatherStation.getPointId());
                if(weatherStation.getWindSpeed()!=null){
                    equipmentinfo.setWindSpeed(weatherStation.getWindSpeed());
                }
                if(weatherStation.getRelativeHumidity()!=null){
                    equipmentinfo.setRelativeHumidity(weatherStation.getRelativeHumidity());
                }
                if(weatherStation.getPressure()!=null){
                    equipmentinfo.setPressure(weatherStation.getPressure());
                }
                /*if(weatherStation.getAmbientTemp()!=null){
                    equipmentinfo.setAmbientTemp(weatherStation.getAmbientTemp());
                }*/
                if(weatherStation.getPrecipitation()!=null){
                    equipmentinfo.setPrecipitation(weatherStation.getPrecipitation());
                }
                if(weatherStation.getPrecipitationIntensity()!=null){
                    equipmentinfo.setPrecipitationIntensity(weatherStation.getPrecipitationIntensity());
                }
            }else {
                LhpDataEquipmentinfoEntity equipmentinfo=new LhpDataEquipmentinfoEntity();
                if(weatherStation.getWindSpeed()!=null){
                    equipmentinfo.setWindSpeed(weatherStation.getWindSpeed());
                }
                if(weatherStation.getRelativeHumidity()!=null){
                    equipmentinfo.setRelativeHumidity(weatherStation.getRelativeHumidity());
                }
                if(weatherStation.getPressure()!=null){
                    equipmentinfo.setPressure(weatherStation.getPressure());
                }
                /*if(weatherStation.getAmbientTemp()!=null){
                    equipmentinfo.setAmbientTemp(weatherStation.getAmbientTemp());
                }*/
                if(weatherStation.getPrecipitation()!=null){
                    equipmentinfo.setPrecipitation(weatherStation.getPrecipitation());
                }
                if(weatherStation.getPrecipitationIntensity()!=null){
                    equipmentinfo.setPrecipitationIntensity(weatherStation.getPrecipitationIntensity());
                }
                dataMap.put(weatherStation.getPointId(),equipmentinfo);
            }
        }
        //安装点名称
        for (LhpInstallationPointEntity point:pointList) {
            LhpDataEquipmentinfoEntity equipmentinfo = dataMap.get(point.getId());
            if (equipmentinfo != null) {
                equipmentinfo.setPointId(point.getId());
                equipmentinfo.setPointName(point.getPointName());
            }
        }
        return dataMap;
    }

    //刷新设备连接列表
    @Override
    public void refreshDataCollectionMap(HashMap<String, DataCollection> map) {
        List<LhpInstallationPointEntity> lipeList = this.list();
        for(LhpInstallationPointEntity lipe : lipeList){
            if(!map.containsKey(lipe.getPointCode())){
                DataCollection dc= new DataCollection(lipe.getId(),lipe.getId(),lipe.getPointCode(),lipe.getPointCode());
                map.put(dc.getSensorNo(), dc);
            }
        }
    }
}
